//
// Created by cjh on 2021/5/22.
//

#include "view.h"
#include <string>
#include <iostream>
#include "http/parser.h"

using namespace std;

static void raise_implementation_error(const char* func_name) {
    string str("HTTP View error: You Must Implementation ");
    str += func_name;
    throw std::runtime_error(str);
}


View::View(Request *request) : request(request) {

}

async<> View::dispatch(Request* request) {
    this->request = request;
    if(request->method() == "GET") {
        cout << "GET" << endl;
        co_await GET(request);
    }else if(request->method() == "POST") {
        co_await POST(request);
    }else if(request->method() == "PUT") {
        co_await PUT(request);
    }else if(request->method() == "HEAD") {
        co_await HEAD(request);
    }else if(request->method() == "PATCH") {
        co_await PATCH(request);
    }else if(request->method() == "DELETE") {
        co_await DELETE(request);
    }
}

async<> View::GET(Request*request) {
    auto response = render(std::string("Method ") + __FUNCTION__ + " Not Allowed", 403);
    co_await request->write(response);
}
async<> View::POST(Request*request) {
    auto response = render(std::string("Method ") + __FUNCTION__ + " Not Allowed", 403);
    co_await request->write(response);
}
async<> View::PUT(Request*request) {
    auto response = render(std::string("Method ") + __FUNCTION__ + " Not Allowed", 403);
    co_await request->write(response);
}
async<> View::HEAD(Request*request) {
    auto response = render(std::string("Method ") + __FUNCTION__ + " Not Allowed", 403);
    co_await request->write(response);
}
async<> View::PATCH(Request*request) {
    auto response = render(std::string("Method ") + __FUNCTION__ + " Not Allowed", 403);
    co_await request->write(response);
}
async<> View::DELETE(Request*request) {
    auto response = render(std::string("Method ") + __FUNCTION__ + " Not Allowed", 403);
    co_await request->write(response);
}


HelloView::HelloView(Request *request) : View(request) {

}

async<> HelloView::GET(Request *request) {
    auto response = render("Hello World!", 403);
    co_await request->write(response);
}
